package com.sskj.bibi.ui.fragment;


import android.annotation.SuppressLint;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding2.widget.RxRadioGroup;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.bibi.R;
import com.sskj.bibi.R2;
import com.sskj.bibi.bean.rxbus.CoinUpdateBean;
import com.sskj.bibi.component.DaggerUserDataComponent;
import com.sskj.bibi.presenter.BibiBuyAndSellFragmentPresenter;
import com.sskj.bibi.util.TipBibiUtil;
import com.sskj.common.base.App;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.depth.bean.DepthData;
import com.sskj.depth.bean.IDepthData;
import com.sskj.depth.view.DepthMapView;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.BibiCoinType;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.BottomSheetUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.NumberUtil;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;

@Route(path = RConfig.BIBI_FRAGMENT_BUY_AND_SELL)//币币交易主页购买区域
public class BibiBuyAndSellFragment extends BaseFragment<BibiBuyAndSellFragmentPresenter> {
    @BindView(R2.id.rbBuy)
    RadioButton rbBuy;
    @BindView(R2.id.rbSell)
    RadioButton rbSell;
    @BindView(R2.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R2.id.spinner)
    TextView spinner;
    @BindView(R2.id.llPriceMode)
    LinearLayout llPriceMode;
    @BindView(R2.id.etPrice)
    EditText etPrice;

    @BindView(R2.id.llAddAndDe)
    LinearLayout llAddAndDe;
    @BindView(R2.id.rlEditPrice)
    RelativeLayout rlEditPrice;
    @BindView(R2.id.llHidePrice)
    LinearLayout llHidePrice;
    @BindView(R2.id.etNum)
    EditText etNum;
    @BindView(R2.id.tvDecrease)
    TextView tvDecrease;
    @BindView(R2.id.tvIncrease)
    TextView tvIncrease;
    @BindView(R2.id.tvCoinType)
    TextView tvCoinType;
    @BindView(R2.id.tvMoney)
    TextView tvMoney;
    @BindView(R2.id.tvTradeMoney)
    TextView tvTradeMoney;
    @BindView(R2.id.btBuy)
    Button btBuy;
    @BindView(R2.id.rgLevel)
    RadioGroup rgLevel;
    @BindView(R2.id.tvNumTitle)
    TextView tvNumTitle;
    @BindView(R2.id.tvMoneyTitle)
    TextView tvMoneyTitle;
    @BindView(R2.id.tvMoneyType)
    TextView tvMoneyType;
    @BindView(R2.id.tvHideMoneyType)
    TextView tvHideMoneyType;
    @BindView(R2.id.tvAllMoneyTitle)
    TextView tvAllMoneyTitle;
    @BindView(R2.id.depthMapView)
    DepthMapView depthMapView;
    @BindView(R2.id.indicatorSeekBar)
    IndicatorSeekBar indicatorSeekBar;
    private String levels = "25,50,75,100";


    @Autowired(required = true)
    String code = "BTC/USDT";//币种类型code
    String type = "BTC";//币种类型
    String moneyType = "USDT";//币种类型
    private BottomSheetDialog priceModeSheet;
    private boolean isBuy = true;
    private boolean isMarketPrice = false;
    private String marketPrice = "5000";//市价
    private String currentPrice = "5000";//限价
    private String usdtMoney = "0";//可用USDT
    private String coinMoney = "0";//可用币
    private String rate = "0.0001";//加减的点
    private String maxTradeCoin = "0";//最大可交易币种数量
    private String fee = "0";//手续费
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private Double level;
    private int numKeepDot;
    private boolean isSetText;


    @Override
    protected int getLayoutId() {
        return R.layout.bibi_fragment_buy_and_sell;
    }

    @Override
    public BibiBuyAndSellFragmentPresenter getPresenter() {
        return new BibiBuyAndSellFragmentPresenter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        btBuy.setBackground(ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.bibi_shape_green : R.drawable.bibi_shape_red));
        ClickUtil.click(btBuy, () -> {
            ARouter.getInstance().build(RConfig.LOGIN_LOGIN).navigation();
        });
        depthMapView.setDrawText(false);
        code = code.replace("_", "/").toUpperCase();
        String substring = code.substring(code.indexOf("/") + 1);
        if (substring.equals("USDT")) {
            rate = "0.000001";
        } else {
            rate = "0.00000001";
        }
//        depthMapView.setSelectBackgroundColor(ContextCompat.getColor(getActivity(), R.color.lib_bg));
//        depthMapView.setSelectTextColor(ContextCompat.getColor(getActivity(),R.color.libTextBlack));
        clearClick();
        initClick();
        updateUI();
//        updateLevelButton();
        LiveDataBus.get().with(RxBusCode.CHANGE_PRICE, String.class)
                .observe(getActivity(), s -> {
                    if (!isMarketPrice) {
                        etPrice.setText(s);
                        etPrice.setSelection(etPrice.getText().toString().length());

                    }
                });

    }

    private void clearClick() {

    }


    /**
     * 更新界面根据
     * 买入卖出，市价限价，币种，可用金额 变化 初始化界面
     */
    private void updateUI() {
        if (radioGroup == null) {
            return;
        }
        numKeepDot = (isBuy && isMarketPrice) ? CoinUtil.getPriceKeepNum(code) : CoinUtil.getNumKeepNum(code);

        int priceKeepDot = CoinUtil.getPriceKeepNum(code);
        tvHideMoneyType.setText(moneyType);
        calculateMaxTrade();
        radioGroup.check(isBuy ? R.id.rbBuy : R.id.rbSell);
        updateIndicator();

        spinner.setText(isMarketPrice ? App.INSTANCE.getString(R.string.bibitipBibiUtil2) : App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment2));
        rlEditPrice.setVisibility(isMarketPrice ? View.GONE : View.VISIBLE);
        llHidePrice.setVisibility(isMarketPrice ? View.VISIBLE : View.GONE);
//        initInputChange();
        etNum.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits((isBuy && isMarketPrice) ? CoinUtil.getPriceKeepNum(code) : CoinUtil.getNumKeepNum(code))});
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(CoinUtil.getPriceKeepNum(code))});
        etPrice.setText(CoinUtil.keepCoinPriceMax2(code, marketPrice));
        etNum.setText("");
        indicatorSeekBar.setProgress(0);
        if (isMarketPrice && isBuy) {
            tvNumTitle.setText(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment3));
        } else {
            tvNumTitle.setText(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment4));
        }
        rgLevel.clearCheck();
        tvMoney.setText(String.format("%s%s", isBuy ? CoinUtil.keepCoinNumMax2(code, usdtMoney) : CoinUtil.keepCoinNumMax2(code, coinMoney), isBuy ? moneyType : type));
        tvCoinType.setText((isBuy && isMarketPrice) ? moneyType : type);
        btBuy.setBackground(ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.bibi_shape_32b_corner10 : R.drawable.bibi_shape_ff5_corner10));
        if (userData != null) {
            btBuy.setText(isBuy ? App.INSTANCE.getString(R.string.bibitipBibiUtil1) : App.INSTANCE.getString(R.string.bibirecordActivity5));
            ClickUtil.click(btBuy, () -> {
                if (checkParam()) {
                    TipBibiUtil.showTradeInfo(getActivity(),
                            isBuy ? App.INSTANCE.getString(R.string.bibitipBibiUtil1) : App.INSTANCE.getString(R.string.bibirecordActivity5),
                            isMarketPrice ? App.INSTANCE.getString(R.string.bibitipBibiUtil2) : App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment2),
                            !isMarketPrice ? etPrice.getText().toString() : "--",
                            isMarketPrice && isBuy ? "--" : etNum.getText().toString(),
                            etNum.getText().toString(),
                            () -> {
                                mPresenter.submit(code, isMarketPrice ? marketPrice : currentPrice, etNum.getText().toString(), isBuy ? "1" : "2", isMarketPrice ? "1" : "2");
                            });
                }
            });
        } else {
            btBuy.setText(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment7));
            ClickUtil.click(btBuy, () -> {
                ARouter.getInstance().build(RConfig.LOGIN_LOGIN).navigation();
            });
        }
        changeShowData();
    }

    private void updateIndicator() {
        indicatorSeekBar.setProgress(0);
        indicatorSeekBar.setThumbDrawable(ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.bibi_shape_slide_green : R.drawable.bibi_shape_slide_red));
        indicatorSeekBar.setTickMarksDrawable(ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.bibi_selector_marks_drawable_green : R.drawable.bibi_selector_marks_drawable_red));
        indicatorSeekBar.setProgressTrackColor(ContextCompat.getColor(App.INSTANCE, isBuy ? R.color.bibi_03c : R.color.bibi_ff5));
    }

    /**
     * 计算最大可输入数量
     */
    private void calculateMaxTrade() {
        if (TextUtils.isEmpty(currentPrice) || Double.valueOf(currentPrice) == 0) {
            maxTradeCoin = "0";
        } else {
            if (isBuy) {
                if (isMarketPrice) {
                    maxTradeCoin = NumberUtil.keepDown(new BigDecimal(usdtMoney).divide(new BigDecimal("1").add(new BigDecimal(fee)), 8, BigDecimal.ROUND_HALF_UP).toString(), CoinUtil.getPriceKeepNum(code), true);
                } else {
                    maxTradeCoin = NumberUtil.keepDown(new BigDecimal(usdtMoney).divide(new BigDecimal("1").add(new BigDecimal(fee)), 8, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(currentPrice), 8, RoundingMode.HALF_UP).toString(), CoinUtil.getNumKeepNum(code), true);
                }
            } else {
                maxTradeCoin = NumberUtil.keepDown(new BigDecimal(coinMoney).toString(), CoinUtil.getNumKeepNum(code), true);
            }
        }

        if (isBuy && isMarketPrice) {
//            indicatorSeekBar.customTickTexts(new String[]{"0", "", "", "", maxTradeCoin + " " + moneyType});
            indicatorSeekBar.customTickTexts(new String[]{"0", "", "", "", CoinUtil.keepCoinNumMax2(code, usdtMoney) + " " + moneyType});
            String s = CoinUtil.keepCoinPrice3(code, new BigDecimal(maxTradeCoin).multiply(new BigDecimal(Math.pow(10, numKeepDot))).toPlainString());
            indicatorSeekBar.setMax(Float.valueOf(s));
            indicatorSeekBar.setProgress(0);

        } else {
            indicatorSeekBar.customTickTexts(new String[]{"0", "", "", "", maxTradeCoin + " " + type});
            String s = CoinUtil.keepCoinPrice3(code, new BigDecimal(maxTradeCoin).multiply(new BigDecimal(Math.pow(10, numKeepDot))).toPlainString());
            indicatorSeekBar.setMax(Float.valueOf(s));
            indicatorSeekBar.setProgress(0);
        }
    }

    /**
     * 检测购买条件
     *
     * @return
     */
    private boolean checkParam() {
        if (TextUtils.isEmpty(SPUtil.get(SPConfig.TOKEN, ""))) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment8));
            return false;
        }
        if (isMarketPrice) {
            if (TextUtils.isEmpty(etNum.getText()) || Double.valueOf(etNum.getText().toString()) == 0) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment9), isBuy ? App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment10) : App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment11)));
                return false;
            }
        } else {
            if (TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment12), isBuy ? App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment10) : App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment11)));
                return false;
            }
            if (TextUtils.isEmpty(etNum.getText()) || Double.valueOf(etNum.getText().toString()) == 0) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment9), isBuy ? App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment10) : App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment11)));
                return false;
            }
        }
        return true;
    }

    /**
     * 根据
     * 价格，数量，滑竿更新交易额
     */
    private void changeShowData() {
        if (TextUtils.isEmpty(etPrice.getText()) || TextUtils.isEmpty(etNum.getText())) {
            if (isBuy) {
                tvAllMoneyTitle.setText(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment13), moneyType));
            } else {
                if (isMarketPrice) {
                    tvAllMoneyTitle.setText(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment14), type));
                } else {
                    tvAllMoneyTitle.setText(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment13), moneyType));
                }
            }
            tvTradeMoney.setText("0");
        } else {
            if (!isMarketPrice) {
                String usdtFull;
                if (isBuy) {
                    usdtFull = new BigDecimal("1").add(new BigDecimal(fee)).multiply(new BigDecimal(etNum.getText().toString())
                            .multiply(new BigDecimal(etPrice.getText().toString()))).toString();
                } else {
                    usdtFull = new BigDecimal("1").multiply(new BigDecimal(etNum.getText().toString()).multiply(new BigDecimal(etPrice.getText().toString()))).toString();
                }
                String usdt;
                if (isBuy) {
                    //限价买入
                    usdt = CoinUtil.keepCoinPrice1(code, usdtFull);
                    tvTradeMoney.setText(usdt);
                    tvAllMoneyTitle.setText(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment15), moneyType));

                } else {//限价卖出
                    usdt = CoinUtil.keepCoinPrice1(code, usdtFull);
                    tvAllMoneyTitle.setText(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment15), moneyType));
                    tvTradeMoney.setText(usdt);
                }
            } else {
                String usdtFull;
                if (isBuy) {
                    usdtFull = new BigDecimal("1").add(new BigDecimal(fee)).multiply(new BigDecimal(etNum.getText().toString())).toString();

                } else {
                    usdtFull = new BigDecimal("1").multiply(new BigDecimal(etNum.getText().toString())).toString();
                }
                String usdt;
                if (isBuy) {
                    //市价买入
                    usdt = CoinUtil.keepCoinPrice1(code, usdtFull);
                    tvAllMoneyTitle.setText(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment15), moneyType));
                    tvTradeMoney.setText(usdt);
                } else {//市价卖出
                    usdt = CoinUtil.keepCoinNumMax3(code, usdtFull);
                    tvAllMoneyTitle.setText(String.format(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment14), type));
                    tvTradeMoney.setText(usdt);
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private void initClick() {
        RxRadioGroup.checkedChanges(radioGroup)
                .subscribe(clickId -> {
                    if (!isBuy && clickId == rbBuy.getId()) {//购买
                        isBuy = true;
//                        isMarketPrice = true;
                        updateUI();
                    } else if (isBuy && clickId == rbSell.getId()) {//出售
                        isBuy = false;
//                        isMarketPrice = true;
                        updateUI();
                    }
                });
//        etNum.setOnFocusChangeListener((v, hasFocus) -> {
//            if (hasFocus) {
//                if (!TextUtils.isEmpty(etNum.getText()) && Double.valueOf(etNum.getText().toString()) == 0) {
//                    etNum.setText("");
//                }
//                rgLevel.clearCheck();
//            }
//        });
        ClickUtil.click(llPriceMode, () -> {
            if (priceModeSheet == null) {
                priceModeSheet = BottomSheetUtil.getBottomSheet(getActivity(), null, (recyclerView, position, v) -> {
                    priceModeSheet.dismiss();
                    if (position == 0 && !isMarketPrice) {
                        isMarketPrice = true;
                        updateUI();
                    } else if (position == 1 && isMarketPrice) {
                        isMarketPrice = false;
                        updateUI();
                    }
                }, App.INSTANCE.getString(R.string.bibitipBibiUtil2), App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment2));
            }
            priceModeSheet.show();
        });
        ClickUtil.click(100, tvDecrease, () -> {
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            String decrease = "-" + rate;
            BigDecimal priceDecimal = new BigDecimal(currentPrice).add(new BigDecimal(decrease));
            if (priceDecimal.doubleValue() <= 0) {
                etPrice.setText("0");
                etPrice.setSelection(etPrice.getText().length());
            } else {
                etPrice.setText(CoinUtil.keepCoinPriceMax2(code, priceDecimal.toString()));
                etPrice.setSelection(etPrice.getText().toString().length());
            }
        });
        ClickUtil.click(100, tvIncrease, () -> {
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            String increase = rate;
            BigDecimal priceDecimal = new BigDecimal(currentPrice).add(new BigDecimal(increase));
            etPrice.setText(CoinUtil.keepCoinPriceMax2(code, priceDecimal.toString()));
            etPrice.setSelection(etPrice.getText().toString().length());


        });

        indicatorSeekBar.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {
                if (seekParams.fromUser) {
                    if (userData == null) {
                        return;
                    }
                    String s = new BigDecimal(seekParams.progressFloat).divide(new BigDecimal(Math.pow(10, numKeepDot)),
                            8, BigDecimal.ROUND_HALF_UP).toPlainString();

                    isSetText = true;
                    String text = (isBuy && isMarketPrice) ? CoinUtil.keepCoinPrice(code, s) : CoinUtil.keepCoinNumMax2(code, s);
                    etNum.setText(text);
                    etNum.setSelection(etNum.getText().toString().length());//将光标移至文字末尾
                    isSetText = false;
                }
            }

            @Override
            public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(IndicatorSeekBar seekBar) {

            }
        });
        initInputChange();
    }

    @SuppressLint("CheckResult")
    private void initInputChange() {
        RxTextView.afterTextChangeEvents(etPrice)
                .subscribe(value -> {
                    String text = value.editable().toString();
                    if (TextUtils.isEmpty(text)) {
                        currentPrice = "0";
                    } else {
                        currentPrice = text;
                    }
                    calculateMaxTrade();
                    changeShowData();
                    etNum.setText(etNum.getText());
                }, e -> System.out.println(e));
        RxTextView.afterTextChangeEvents(etNum)
                .subscribe(value -> {
                    if (userData == null) {
//                        ToastUtil.showShort(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment8));
                        return;
                    }
                    String text = value.editable().toString();
                    if (TextUtils.isEmpty(text) || Double.valueOf(text) == 0 ||
                            TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                        indicatorSeekBar.setProgress(0);
                    } else {
                        if (Double.valueOf(text) > Double.valueOf(maxTradeCoin)) {
                            etNum.setText(maxTradeCoin);
//                            ToastUtil.showShort(App.INSTANCE.getString(R.string.bibibibiBuyAndSellFragment16));
                        } else {
                            if (!isSetText) {
                                String s = new BigDecimal(text).multiply(new BigDecimal(Math.pow(10, numKeepDot))).toPlainString();
                                indicatorSeekBar.setProgress(Float.valueOf(s));
                            }
//                            int progress = new BigDecimal(text).divide(new BigDecimal(maxTradeCoin), 8, RoundingMode.HALF_UP).multiply(new BigDecimal("1000")).intValue();
//                            progress = progress > 1000 ? 1000 : progress;
                        }
                    }
                    changeShowData();
                });
    }

    /**
     * 动态更新杠杆按钮
     */
//    private void updateLevelButton() {
//        if (rgLevel == null) {
//            return;
//        }
//        rgLevel.removeAllViews();
//        if (TextUtils.isEmpty(levels))
//            return;
//        Flowable.fromArray(levels.split(","))
//                .subscribe(s -> {
//                    RadioButton radioButton = new RadioButton(getActivity());
//                    radioButton.setBackgroundResource(R.drawable.bibi_percent);    // 设置RadioButton的背景图片
//                    radioButton.setButtonDrawable(null);            // 设置按钮的样式
//                    radioButton.setText(s + "%");
//                    radioButton.setGravity(Gravity.CENTER);
//                    radioButton.setWidth(0);
//                    radioButton.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.commonWhite));
//                    radioButton.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
//                    rgLevel.addView(radioButton, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//
//                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) radioButton.getLayoutParams();
//                    layoutParams.weight = 1;
//                    layoutParams.leftMargin = (int) RudenessScreenHelper.pt2px(App.INSTANCE, 5);
//                    layoutParams.rightMargin = (int) RudenessScreenHelper.pt2px(App.INSTANCE, 5);
//                    radioButton.setLayoutParams(layoutParams);
//                });
////        rgLevel.check(rgLevel.getChildAt(0).getid());
//    }
    @Override
    public void initData() {
        mPresenter.getCoinInfo(code, userData);
        mPresenter.getDepthData(code);
        mPresenter.initSocket(code);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
            mPresenter.getCoinInfo(code, userData);
            updateUI();
        });
    }

    /**
     * 更换币种,更改市价限价
     *
     * @param coinType
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeCoin(BibiCoinType coinType) {

        code = coinType.getCode();
        int priceKeepNum = CoinUtil.getPriceKeepNum(code);
        double rateInit = 1;
        while (priceKeepNum > 0) {
            rateInit *= 10;
            priceKeepNum--;
        }
        rate = 1d / rateInit + "";
        moneyType = code.replace("_", "/").split("/")[1].toUpperCase();
        type = code.replace("_", "/").split("/")[0].toUpperCase();
        isMarketPrice = false;
        isBuy = true;
        refresh();
    }

    /**
     * 刷新页面
     */
    @Subscribe(code = RxBusCode.BIBI_FRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        mPresenter.getCoinInfo(code, userData);
        mPresenter.getDepthData(code);
        mPresenter.sendCode(code);
    }


    public void updateCoinData(CoinUpdateBean coinUpdateBean) {
        currentPrice = marketPrice = coinUpdateBean.getMarketPrice();
        usdtMoney = coinUpdateBean.getUsdtMoney();
        coinMoney = coinUpdateBean.getCoinMoney();
        int priceKeepNum = CoinUtil.getPriceKeepNum(code);
        double rateInit = 1;
        while (priceKeepNum > 0) {
            rateInit *= 10;
            priceKeepNum--;
        }
        rate = 1d / rateInit + "";
        moneyType = TextUtils.isEmpty(code) ? "" : code.replace("_", "/").split("/")[1].toUpperCase();
        type = TextUtils.isEmpty(code) ? "" : code.replace("_", "/").split("/")[0].toUpperCase();
        fee = new BigDecimal(coinUpdateBean.getFee()).multiply(new BigDecimal("1")).toPlainString();
//        levels = coinUpdateBean.getLevels();
//        updateLevelButton();
        updateUI();

    }

    /**
     * 更新深度图
     *
     * @param data
     */
    public void updateDeep(WSFiveBean data) {
        if (data == null) {
            data = new WSFiveBean();
            data.setCode(code);
            data.setBids(new ArrayList<>());
            data.setAsks(new ArrayList<>());
        }
        Collections.reverse(data.getAsks());
        Collections.reverse(data.getBids());
        Flowable<List<IDepthData>> buyFlow = Flowable.fromIterable(data.getBids())
                .map(fiveBean -> (IDepthData)new DepthData(fiveBean.getDoubleTotalSize()+"", fiveBean.getPrice()))
                .toList()
                .toFlowable();
        Flowable<List<IDepthData>> sellFlow = Flowable.fromIterable(data.getAsks())
                .map(fiveBean -> (IDepthData)new DepthData(fiveBean.getDoubleTotalSize()+"", fiveBean.getPrice()))
                .toList()
                .toFlowable();

        Flowable.zip(buyFlow, sellFlow, (buyData, sellData) -> {
            if (depthMapView != null) {
                if (code.toUpperCase().contains("DIG")) {
                    depthMapView.mPriceLimit = 6;
                    depthMapView.mVolumeLimit = 6;
                } else {
                    depthMapView.mPriceLimit = CoinUtil.getPriceKeepNum(code);
                    depthMapView.mVolumeLimit = CoinUtil.getNumKeepNum(code);
                }
                depthMapView.setData(buyData, sellData);
            }
            return "1";
        }).subscribe(s -> {
        }, e -> {
            System.out.println(e);
        });
    }

    public void buySuccess() {
        RxBus.getDefault().send(RxBusCode.BIBI_FRESH);
//        ARouter.getInstance().build(RConfig.BIBI_RECORD).navigation();
    }


}
